<script setup lang="ts">
import { computed, ref } from 'vue'

import { onLoad } from '@dcloudio/uni-app'
import { pageStoreAPI, pageStoreCollectAPI } from '@/services/store'
import type { IstorePageParam, IstoreItem } from '@/types/store'

import { useStore, useMemberStore } from '@/stores'
const { getLocalAddressLatAndLog, getStoreInfo, changeStoreInfo } = useStore()
const { getUserInfo } = useMemberStore()

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 引入百度地图API
// eslint-disable-next-line no-undef
const bmap = require('../../static/js/bmap-wx.min.js')
const BMapWX = bmap.BMapWX
//    这个地方是你在百度地图中申请的ak
var BMap = new BMapWX({ ak: 'hOtF9JR4wCD5SSQGKhddv4IsHildEpVF' })
const initParams: any = {
  page: 1,
  limit: 5,
}
// 接收页面参数
const query = defineProps<{
  latitude: number
  longitude: number
}>()
const params = ref({
  page: initParams.page,
  limit: initParams.limit,
  latitude: query.latitude,
  longitude: query.longitude,
} as IstorePageParam)

const storeList = ref([] as IstoreItem[])

onLoad(async () => {
  storeList.value = []
  params.value = {
    ...params.value,
    page: initParams.page,
    limit: initParams.limit,
  }
  await request()
})

const showLocationMap = () => {
  // 显示地图
  uni.getLocation({
    type: 'gcj02', // 'wgs84', //
    isHighAccuracy: true,
    geocode: true,
    success: async (res: any) => {
      params.value.latitude = res.latitude
      params.value.longitude = res.longitude
      const resStoreList = await pageStoreAPI({ ...params.value })
      storeList.value = resStoreList.data.list
      setMarkers()
    },
    fail: (res: any) => {
      console.error(res)
    },
    complete: (res: any) => {},
  })
}
// 响应式数据
const markers = ref([] as any[])
const setMarkers = () => {
  markers.value = storeList.value.map((item: any, index: number) => {
    return {
      title: item.storeName,
      address: item.address,
      alpha: 1,
      width: 30,
      height: 30,
      id: index,
      storeId: item.storeId,
      telephone: '(0350)2118666',
      latitude: item.latitude,
      longitude: item.longitude,
      iconPath: '../../static/img/red_marker.png',
      iconTapPath: '../../static/img/red_marker.png',
      label: item.storeName,
      callout: {
        content: item.storeName,
        display: 'ALWAYS',
      },
    }
  })
  latitude.value = storeList.value[0].latitude
  longitude.value = storeList.value[0].longitude
  console.log(markers.value)
}
const latitude = ref(0)
const longitude = ref(0)
const rgcData = ref({})

const addresshandle = () => {
  getLocationByAddress('山西省忻州市忻府区小檀幼儿园')
}

const regeocodingHandler = () => {
  const fail = (data: any) => {
    console.error('百度地图API调用失败：', data)
    uni.showToast({
      title: '定位失败',
      icon: 'error',
    })
  }

  const success = (data: any) => {
    console.log('百度地图返回数据：', data)

    // 提取标记数据
    markers.value = data.wxMarkerData.map((item: any) => {
      return {
        ...item,
        latitude: item.latitude,
        longitude: item.longitude,
        iconPath: '../../static/img/red_marker.png',
        iconTapPath: '../../static/img/red_marker.png',
        width: 30,
        height: 30,
      }
    })
    console.log(markers.value)
    if (data.wxMarkerData && data.wxMarkerData.length > 0) {
      latitude.value = data.wxMarkerData[0].latitude
      longitude.value = data.wxMarkerData[0].longitude
      rgcData.value = data.originalData?.result || {}
    } else {
      uni.showToast({ title: '未返回有效位置', icon: 'none' })
    }
  }
  // 发起regeocoding检索请求
  BMap.regeocoding({
    location: `${latitude.value},${longitude.value}`,
    coordtype: 'gcj02ll', // 输入坐标是 GCJ-02 火星坐标
    ret_coordtype: 'gcj02ll', // 返回结果也使用 GCJ-02 坐标
    radius: 1000, // 搜索半径 1000 米
    fail: fail,
    success: success,
    iconPath: '../../static/img/red_marker.png',
    iconTapPath: '../../static/img/red_marker.png',
  })
}
const searchHandler = () => {
  const fail = (data: any) => {
    console.error('百度地图API调用失败：', data)
    uni.showToast({
      title: '定位失败',
      icon: 'error',
    })
  }

  const success = (data: any) => {
    console.log('百度地图返回数据：', data)

    // 提取标记数据
    markers.value = data.wxMarkerData.map((item: any) => {
      return {
        ...item,
        latitude: item.latitude,
        longitude: item.longitude,
        iconPath: '../../static/img/red_marker.png',
        iconTapPath: '../../static/img/red_marker.png',
        width: 30,
        height: 30,
      }
    })
    console.log(markers.value)
    if (data.wxMarkerData && data.wxMarkerData.length > 0) {
      latitude.value = data.wxMarkerData[0].latitude
      longitude.value = data.wxMarkerData[0].longitude
      rgcData.value = data.originalData?.result || {}
    } else {
      uni.showToast({ title: '未返回有效位置', icon: 'none' })
    }
  }
  // 发起regeocoding检索请求
  BMap.search({
    query: '饭店',
    fail: fail,
    success: success,
    iconPath: '../../static/img/red_marker.png',
    iconTapPath: '../../static/img/red_marker.png',
  })
}

const markertap = (info: any) => {
  const storeId = markers.value.find((v) => v.id === info.detail.markerId)?.storeId
  uni.navigateTo({ url: '/pagesStore/detail/detail?id=' + storeId })
}

// 根据地址获取坐标并显示标记
const getLocationByAddress = (address: string) => {
  // const BMap = new bmap.BMapWX({ ak: 'hOtF9JR4wCD5SSQGKhddv4IsHildEpVF' })

  const fail = (data: any) => {
    console.error('百度地图API调用失败：', data)
    uni.showToast({
      title: '定位失败',
      icon: 'error',
    })
  }

  const success = (data: any) => {
    console.log('百度地图返回数据：', data)

    // 提取标记数据
    const wxMarkerData = data.wxMarkerData

    if (wxMarkerData && wxMarkerData.length > 0) {
      const firstMarker = wxMarkerData[0]

      markers.value = wxMarkerData.map((item: any) => ({
        id: item.id,
        latitude: item.latitude,
        longitude: item.longitude,
        title: item.title,
        iconPath: item.iconPath, // 自定义图标
        width: 30,
        height: 30,
      }))

      latitude.value = firstMarker.latitude
      longitude.value = firstMarker.longitude
      rgcData.value = data.originalData?.result || {}
    } else {
      uni.showToast({ title: '未返回有效位置', icon: 'none' })
    }
  }

  // 发起地理编码请求（地址 → 坐标）
  BMap.geocoding({
    address,
    success,
    fail,
    // 可选：自定义图标
    iconPath: '../../static/img/red_marker.png',
    iconTapPath: '../../static/img/red_marker.png',
  })
}

// tabs 数据
const orderTabs = ref([
  { orderState: 0, title: '选择门店' },
  { orderState: 1, title: '常用/收藏' },
])

// 高亮下标
// const activeIndex = ref(orderTabs.value.findIndex((v) => v.orderState === Number(0)))
const activeIndex = ref(0 as number)
const statusClass = (number: number) => {
  let str = ''
  switch (number) {
    case 1:
      str = 'status01'
      break
    case 2:
      str = 'status02'
      break
    case 3:
      str = 'status03'
      break
    default:
      str = 'status04'
  }
  return str
}

const goToOrder = (item: IstoreItem) => {
  changeStoreInfo(item)
  uni.switchTab({
    url: `/pages/category/category`,
  })
}

const onTabHandler = async (index: number) => {
  activeIndex.value = index
  storeList.value = []
  params.value = {
    ...params.value,
    page: initParams.page,
    limit: initParams.limit,
  }
  await request()
}

const triggered = ref(false) // 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
const noMore = ref(false)
const total = ref(0)
const finish = ref(false)

const onPulling = (e: any) => {
  if (e.detail.deltaY < 50) return // 防止上滑页面也触发下拉
  triggered.value = true
}
// 自定义下拉刷新被复位
const onRestore = () => {
  triggered.value = false
}
// 自定义下拉刷新被中止
const onAbort = () => {
  console.error('onAbort')
}
// 自定义下拉刷新被触发
const onRefresh = async () => {
  if (finish.value === true) {
    return
  }
  storeList.value = []
  params.value = {
    ...params.value,
    page: initParams.page,
    limit: initParams.limit,
  }
  await request()
}

// 滚动触底
const onScrolltolower = async () => {
  if (finish.value === true) {
    return
  }
  if (storeList.value.length < total.value) {
    params.value.page = params.value.page + 1
  } else {
    noMore.value = true
    return
  }
  await request()
}

const request = async () => {
  if (finish.value === true) {
    return
  }
  finish.value = true
  let res: any = null
  if (activeIndex.value === 0) {
    res = await pageStoreAPI({ ...params.value })
  } else {
    res = await pageStoreCollectAPI({
      ...params.value,
      userId: getUserInfo()?.id,
    })
  }
  storeList.value = [...storeList.value, ...res.data.list]
  total.value = res.data.total
  setMarkers()
  finish.value = false
  triggered.value = false
}
</script>

<template>
  <view class="store-list-page">
    <view class="map_container">
      <map
        class="map"
        id="map"
        style="width: 100%; height: 500rpx"
        :latitude="latitude"
        :longitude="longitude"
        :scale="14"
        :show-location="false"
        :markers="markers"
        @markertap="markertap"
      ></map>
    </view>
    <!-- <view class="rgc_info">
      <text>经纬度：{{ latitude }},{{ longitude }}</text>
    </view>
    <view>
      <view @tap="addresshandle">地址编码</view>
      <view @tap="regeocodingHandler">地址解析</view>
      <view @tap="searchHandler">POI检索</view>
      <view @tap="showLocationMap">showLocationMap</view> activeIndex = index
    </view> -->
    <view class="tabs">
      <text
        class="item"
        :class="{ active: activeIndex === index }"
        v-for="(item, index) in orderTabs"
        :key="item.title"
        @tap="onTabHandler(index)"
      >
        {{ item.title }}
      </text>
      <!-- 游标 -->
      <view class="cursor" :style="{ left: activeIndex * 50 + '%' }"></view>
    </view>
    <!-- 滑动容器 -->
    <swiper
      class="swiper"
      :current="activeIndex"
      @change="(e:any) => onTabHandler(e.detail.current)"
    >
      <!-- 滑动项 -->
      <swiper-item v-for="item in orderTabs" :key="item.title">
        <scroll-view
          scroll-y
          class="store-main"
          enable-back-to-top
          @scrolltolower="onScrolltolower"
          :refresher-enabled="true"
          :refresher-triggered="triggered"
          :refresher-threshold="100"
          refresher-background="#F5F5F7"
          @refresherpulling="onPulling"
          @refresherrefresh="onRefresh"
          @refresherrestore="onRestore"
          @refresherabort="onAbort"
        >
          <view class="store-content" v-for="(item, index) in storeList" :key="index">
            <view class="icon">
              <text class="iconfont icon-bianlidian"></text>
            </view>
            <navigator
              class="con"
              :url="`/pagesStore/detail/detail?id=${item.storeId}`"
              hover-class="none"
            >
              <text class="title">{{ item.storeName }}</text>
              <text class="address">{{ item.address }}</text>
            </navigator>
            <view class="operation">
              <text class="distance">{{ item.distanceKm }}km</text>
              <text class="btn" @tap="goToOrder(item)">去点单</text>
            </view>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';
page {
  height: 100%;
  overflow: hidden;
}

.store-list-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: $background-color;

  .tabs {
    display: flex;
    justify-content: space-around;
    line-height: 60rpx;
    margin: 0 10rpx;
    background-color: #fff;
    box-shadow: 0 4rpx 6rpx rgba(240, 240, 240, 0.6);
    position: relative;
    z-index: 9;

    .item {
      flex: 1;
      text-align: center;
      padding: 20rpx;
      font-size: 28rpx;
      color: $font-color;
      font-weight: $font-medium-weight;

      &.active {
        color: $green-color;
      }
    }

    .cursor {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 50%;
      height: 6rpx;
      padding: 0 50rpx;
      box-sizing: border-box;
      background-color: $green-color;
      /* 过渡效果 */
      transition: all 0.4s;
    }
  }

  .swiper {
    background-color: #f7f7f8;
    .store-main {
      flex: 1;
      padding-bottom: 60rpx;
      /* 针对 H5 端 */
      ::-webkit-scrollbar {
        display: none; /* 隐藏滚动条 */
      }
    }
  }
}

.store-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx;
  border: 1px solid #f3f4f6;
  background: #fff;
  margin: 32rpx 32rpx 0 32rpx;
  border-radius: 32rpx;

  .icon {
    margin-bottom: auto;
    text {
      font-size: 34rpx;
    }
  }

  .con {
    flex-grow: 1;
    flex: 1;
    margin-left: 32rpx;
    display: flex;
    flex-direction: column;
    margin-right: 10rpx;

    .title {
      font-size: $font-medium-size;
      color: $good-font-title-color;
      font-weight: $font-medium-weight;
      margin-bottom: 14rpx;
      @include lines-ellipsis-style(1);
    }

    .address {
      font-size: $font-size;
      color: $font-color;
      font-weight: $font-weight;
      @include lines-ellipsis-style(1);
    }
  }

  .operation {
    display: flex;
    flex-direction: column;
    justify-content: right;
    .distance {
      font-size: $font-size;
      color: $good-font-con-color;
      margin-bottom: 14rpx;
      text-align: right;
    }

    .btn {
      height: 64rpx;
      line-height: 64rpx;
      font-size: $font-size;
      color: #fff;
      background-color: #2e8b57;
      padding: 0 32rpx;
      border-radius: 32rpx;
    }
  }
}

// 订单列表
.orders {
  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    .name {
      height: 80rpx;
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 10rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      width: 180rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      border: 1rpx solid #ccc;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
